package com.woniu.web.exception;

import com.woniu.core.exception.WoniuxyException;
import com.woniu.core.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
//处理异常在这里抓住
@Slf4j
public class GlobalExceptionHandler {

    //捕捉令牌异常
    @ExceptionHandler(Throwable.class)
    public Result handleThrowableException(Throwable e) throws Exception {
       log.error("服务异常",e);
       // e.printStackTrace();
        return Result.getResult(String.class).setMsg("系统错误").setCode(500);
    }

    @ExceptionHandler(WoniuxyException.class)
    public Result handleWoniuxyException(WoniuxyException e) throws Exception {
        log.error("服务异常",e);
        //打印错误信息
        //e.printStackTrace();
        return Result.getResult(String.class).setMsg(e.getMessage()).setCode(e.getCode());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException ex) throws Exception {
        List<String> errors = new ArrayList<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            ex.printStackTrace();
            return Result.getResult(String.class).setMsg(error.getDefaultMessage());
        }
        return Result.getResult(String.class).setMsg(ex.getMessage());
    }

}
